package com.ruoyi.web.controller.common;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.RsaUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

@RestController
public class RSAKeyController {

    @Autowired
    private RedisCache redisCache;


    @GetMapping("/pairKey/gen")
    public AjaxResult getPublicKey(@RequestParam("uuid") String uuid) throws NoSuchAlgorithmException {
        RsaUtils.AsymmetricKeyPair keyPair = RsaUtils.generateAsymmetricKeyPair(RsaUtils.Algorithm.Encryption.RSA_ECB_PKCS1);
        String privateKey = keyPair.getPrivateKey();
        String publicKey = keyPair.getPublicKey();
        String privateKeyRedis = Constants.PRIVATE_KEY_KEY + uuid;
        String publiceKeyRedis = Constants.PUBLIC_KEY_KEY + uuid;
        redisCache.setCacheObject(privateKeyRedis, privateKey, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        redisCache.setCacheObject(publiceKeyRedis, publicKey, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("publicKey",publicKey);
        return ajax;
    }

}
